package com.zglc.ms.shop.controller.log;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.zglc.ms.shop.filter.JwtHelper;

/**
 * 用户个人信息字段更新切面(拦截器) 用于记录用户更新的字段信息(更新用户, 初始值, 修改后的值和更新时间)
 */
@Component
@Aspect
public class RequestLogAspect {

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Pointcut("@annotation(com.zglc.ms.shop.controller.log.RequestLog)")
	public void requestLogAspect() {

	}

	/**
	 * 用于拦截用户修改操作(后置通知): (被拦截的方法参数属性必须是userId, oldValue, newValue)
	 * 
	 */
	@Around("requestLogAspect()")
	public Object requestLogAspect(ProceedingJoinPoint joinPoint) throws Exception {
		String targetName = joinPoint.getTarget().getClass().getName();
		String methodName = joinPoint.getSignature().getName();
		Object[] arguments = joinPoint.getArgs();
		String argStr = "";
		if (arguments != null) {
			for(int i = 0; i < arguments.length; i++){
				argStr += (arguments[i] + "， ");
			}
		}
		
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		Integer userId = JwtHelper.getUserId(request);
		String openId = JwtHelper.getOpenId(request);
		
		try {
			// 前置通知
			Object result = joinPoint.proceed();// 返回通知
			
			String showResult = result.toString();
			if(!StringUtils.isEmpty(showResult)&&showResult.length() >= 1000){
				showResult = showResult.substring(0, 1000);
			}
			
			logger.info("RequestInfo request: targetName = " + targetName + "." + methodName + " arguments " + argStr + 
					" userId " + userId + "openId " + openId  + " response: " + showResult);
			return result;
		} catch (Throwable e) {
			e.printStackTrace();
		} finally {
		}

		return null;
	}

}